package dabs.ginterface;

import dabs.engine.*;
import dabs.engine.control.GameCommand;
import dabs.engine.control.ReadCommand;
import dabs.engine.messaging.Notification;
import dabs.engine.messaging.NotificationHandler;

import java.io.*;



public class GameInterface implements Runnable, NotificationHandler {
	private GameEngine geng;
	private CommandParser parser; 
	
	public GameInterface(GameEngine geng) {
		this.geng = geng;
		this.parser = new CommandParser();
		geng.registerInterface(this);
	}

	synchronized public void handleNotification(Notification notif) {
		if (notif.getSource().isEmpty()) {
			System.out.println(notif.getDescription());
		} else {
			System.out.println("Notif from " + notif.getSource() + ": " + notif.getDescription());
		}
		
	}

	// process a single command;
	private void processCommand(String command) {
		
		if (parser.type(command).equals("gamecommand")) {	
			
			GameCommand gc = parser.asGameCommand(command);
			
			// if it's getval we don't send it to the engine
			if (gc.getCommand().equals("getval")) {
				System.out.println(geng.getValue());
			} else {
				geng.runCommand(gc);
			}
			
		} else if (parser.type(command).equals("componentcommand")) {
			geng.getOperatorSoftware().runCommand(parser.asComponentCommand(command));
		
		} else if (parser.type(command).equals("read")) {
			ReadCommand rc = parser.asReadCommand(command);
			try {
				System.out.println(geng.getPowerPlant().getComponent(rc.getDestination()).getAttribute(rc.getAttribute()));
			} catch (Exception e) {
				System.out.println("Component / attribute not found");
			}
		
		} else if (command.equals("list")) {
			System.out.println(geng.getPowerPlant().getNameList());
		
		} else if (command.equals("help")) {
			System.out.println("Try 'save', 'load', 'getval', 'read compname steam', 'read compname water', 'list', 'valvename toggle', 'print'");
		
		} else if (command.equals("print")) {
			geng.getPowerPlant().print();
		}
		else {
			System.out.println("Command not found. Try help");
		}

	}
	
	public void run() {
		System.out.println("Starting bunny attack prototype. To start, type help");
		InputStreamReader isr = new InputStreamReader(System.in);
		BufferedReader br = new BufferedReader(isr);
		
		try {
			// run as long as the game engine is running
			while(!geng.isStopped()) {
				String command = br.readLine();
				processCommand(command);
			}
		} catch (Exception e) {
			System.out.println("Exception " + e + " caught");
		}
	}
}
